/*socket.js
-conection
-api zum senden/empfangen, send(object msg), register(callBack Function, [string comand])
*/
function socket(game, url){
	var socket;
	var listeners = new Array();
	var host = url;
	var self = this;
	try{
		socket = new WebSocket(host);
	}catch(ex){
		try{
			socket = new MozWebSocket(host);
		}catch (e) {
			return false;
		}
	}
	socket.onmessage = function(msg){
		//pong.receive($.evalJSON(msg.data))
		var msg = $.evalJSON(msg.data);
		self.notify(msg[0], msg);
	}
	socket.onclose = function(msg){
		game.onclose(msg);
		//this.readyState
	};
	socket.onopen = function(msg){
		game.onopen(msg);
		//this.readyState
	};
	socket.onerror = function(error){
		//console.log(error);
	};


	this.attach = function(listner, name){
		if( typeof(name) == 'string' ){
			listeners[name] = listner;
		}
		if( name instanceof Array ){
			$(name).each(function(key, value){
				listeners[value] = listner;
			});
		}
		
	}
	// detach noch nicht getestet
	this.detach = function(name){
		if( typeof(name) == 'string' ){
			name = new Array(name);
		}
		var i = 0;
		$(name).each(function(key,value){
			if(value in listeners){
				listeners.slice(i, 1);
			}
			i++;
		});
	}
	this.notify = function(listner,msg){
		listeners[listner].update(msg);
	}

	this.send = function(command, target, data){
		msg = new Array(command, target, data)
		msg = jQuery.toJSON(msg);
		try{ socket.send(msg);  }catch(ex){ }
		msg = null;
	}

	this.quit = function(){
		socket.close();
		socket=null;
	}

}